const menuService = require('../services/menuService');
const { success, successWithData, error } = require('../utils/resultwrapper');

class MenuController {
    /**
     * 创建菜单
     */
    async createMenu(req, res) {
        try {
            const menuData = req.body;
            const result = await menuService.createMenu(menuData);
            res.json(successWithData(result));
        } catch (err) {
            res.json(error(err.message));
        }
    }

    /**
     * 更新菜单
     */
    async updateMenu(req, res) {
        try {
            const { id } = req.params;
            const menuData = req.body;
            const result = await menuService.updateMenu(id, menuData);
            res.json(successWithData(result));
        } catch (err) {
            res.json(error(err.message));
        }
    }

    /**
     * 删除菜单
     */
    async deleteMenu(req, res) {
        try {
            const { id } = req.params;
            const result = await menuService.deleteMenu(id);
            res.json(success(result));
        } catch (err) {
            res.json(error(err.message));
        }
    }

    /**
     * 获取菜单详情
     */
    async getMenuById(req, res) {
        try {
            const { id } = req.params;
            const result = await menuService.getMenuById(id);
            res.json(successWithData(result));
        } catch (err) {
            res.json(error(err.message));
        }
    }

    /**
     * 获取菜单树
     */
    async getMenuTree(req, res) {
        try {
            const result = await menuService.getMenuTree(req.query);
            res.json(successWithData(result));
        } catch (err) {
            res.json(error(err.message));
        }
    }

    /**
     * 获取角色菜单列表
     */
    async getRoleMenus(req, res) {
        try {
            const { roleId } = req.params;
            const result = await menuService.getRoleMenus(roleId);
            res.json(successWithData(result));
        } catch (err) {
            res.json(error(err.message));
        }
    }

    /**
     * 获取Vue3路由格式的菜单树
     */
    async getVueRoutes(req, res) {
        try {
            const userId = req.user.id;
            const result = await menuService.getVueRoutes(userId);
            res.json(successWithData(result));
        } catch (err) {
            res.json(error(err.message));
        }
    }

    /**
     * 获取菜单下拉选项
     */
    async getMenuOptions(req, res) {
        try {
            const { onlyParent = false } = req.query;
            const result = await menuService.getMenuOptions(onlyParent);
            res.json(successWithData(result));
        } catch (err) {
            res.json(error(err.message));
        }
    }
}

module.exports = new MenuController();